<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\image;


use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\font\FontModel;
use plugin\admin\app\model\image\ImageServerManageModel;
use support\Redis;
use support\Request;
use support\Response;

class ImageServerManageLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new ImageServerManageModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        $request->inputSet('isdel','0');
        return parent::select($request);
    }

    public function insert(Request $request): Response
    {
        if(!empty($request->input('ip'))){
            $domain = 'http://'.$request->input('ip').':9999/';
            $request->inputSet('domain',$domain);
        }
        return parent::insert($request);
    }

    protected function doInsert($data)
    {
        $id = parent::doInsert($data);
        $this->cacheServer();
        return $id;
    }

    public function update(Request $request): Response
    {
        if(!empty($request->input('ip'))){
            $domain = 'http://'.$request->input('ip').':9999/';
            $request->inputSet('domain',$domain);
        }
        return parent::update($request);
    }

    protected function doUpdate($id, $data)
    {
        parent::doUpdate($id, $data);
        $this->cacheServer();
    }

    public function delete(Request $request): Response
    {
       return parent::isDelete($request);
    }

    protected function doIsDelete($ids)
    {
        parent::doIsDelete($ids);
        $this->cacheServer();
    }

    protected function cacheServer()
    {
        $data = $this->model->getWhere(['status'=>1,'isdel'=>0])->get();
        $aiImageServersUser = [];
        $aiImageServersAdmin = [];
        foreach($data as $val){
            if($val['type']==1){
                $aiImageServersUser[] = ['domain'=>$val['domain'],'ip'=>$val['ip']];
            }elseif($val['type']==2){
                $aiImageServersAdmin[] = ['domain'=>$val['domain'],'ip'=>$val['ip']];
            }
        }
        Redis::connection('ai_image_cache')->set('ai_image_server_manage_user',json_encode($aiImageServersUser));
        Redis::connection('ai_image_cache')->set('ai_image_server_manage_admin',json_encode($aiImageServersAdmin));

        return true;
    }
}